layui.config({
	base : "js/"
}).use(['form','layer','jquery','laypage'],function(){
	var form = layui.form(),
		layer = parent.layer === undefined ? layui.layer : parent.layer,
		laypage = layui.laypage,
		$ = layui.jquery;

	//http://localhost/ci/public/static/json/usersList.json
	//http://localhost/ci/admin/user/imp_index
	//加载页面数据
	var usersData = '';
	$.get("http://localhost/ci/admin/user/imp_index", {'token':localStorage.token,'user_token':localStorage.user},  function(data){
		//执行加载数据的方法
        usersData = JSON.parse(data);
        // console.log(data);
        if(data == '0'){

            top.location = 'http://localhost/ci/login/login/login';//整个页面进行跳转
        }
        usersData = JSON.parse(data)['data'];
        //console.log(data);
		usersList();
	})


    //全选
	form.on('checkbox(allChoose)', function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		child.each(function(index, item){
			item.checked = data.elem.checked;
		});
		form.render('checkbox');
	});

	//通过判断文章是否全部选中来确定全选按钮是否选中
	form.on("checkbox(choose)",function(data){
		var child = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"])');
		var childChecked = $(data.elem).parents('table').find('tbody input[type="checkbox"]:not([name="show"]):checked')
		if(childChecked.length == child.length){
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = true;
		}else{
			$(data.elem).parents('table').find('thead input#allChoose').get(0).checked = false;
		}
		form.render('checkbox');
	})

	function usersList(){
		//渲染数据
		function renderDate(data,curr){
			var dataHtml = '';
			currData = usersData.concat().splice(curr*nums-nums, nums);
			if(currData.length != 0){
				for(var i=0;i<currData.length;i++){
					dataHtml += '<tr>'
			    	+  '<td><input type="checkbox" name="checked" lay-skin="primary" lay-filter="choose"></td>'
			    	+  '<td>'+currData[i].username+'</td>'
			    	+  '<td>'+currData[i].email+'</td>'
			    	+  '<td>'+currData[i].mobile+'</td>'
			    	+  '<td>'+currData[i].status+'</td>'
			    	+  '<td>'+currData[i].create_time+'</td>'
			    	+  '<td>'
					+    '<a class="layui-btn layui-btn-mini users_edit" data-id="'+currData[i].user_id+'"><i class="iconfont icon-edit"></i> 编辑</a>'
					+    '<a class="layui-btn layui-btn-danger layui-btn-mini users_del" data-id="'+currData[i].user_id+'"><i class="layui-icon">&#xe640;</i> 删除</a>'
					+    '<a class="layui-btn layui-btn-danger layui-btn-mini role_edit" data-id="'+currData[i].user_id+'"><i class="layui-icon"></i> 角色</a>'
			        +  '</td>'
			    	+'</tr>';
				}
			}else{
				dataHtml = '<tr><td colspan="8">暂无数据</td></tr>';
			}
		    return dataHtml;
		}

		//分页
		var nums = 13; //每页出现的数据量
		laypage({
			cont : "page",
			pages : Math.ceil(usersData.length/nums),
			jump : function(obj){
				$(".users_content").html(renderDate(usersData,obj.curr));
				$('.users_list thead input[type="checkbox"]').prop("checked",false);
		    	form.render();
			}
		})
	}

//--------------弹出页面------------------
    //操作
    $("body").on("click",".users_edit",function(){  //编辑
        var _this = $(this);
        $('.ci_data').val(_this.attr('data-id'));
        var index = layui.layer.open({
            title : "修改会员",
            type : 2,
            area: ['600px', '360px'],
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            content : "http://localhost/ci/admin/user/updateUser",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        /*$(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);*/
        /*layer.alert('您点击了会员编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。',{icon:6, title:'文章编辑'});*/
    })

    $("body").on("click",".users_del",function(){  //删除
        var _this = $(this);
        layer.confirm('确定删除此用户吗？',{icon:3, title:'提示信息'},function(index){
            //_this.parents("tr").remove();
            for(var i=0;i<usersData.length;i++){
                if(usersData[i].user_id == _this.attr("data-id")){
                    //usersData.splice(i,1);
                    //usersList(usersData);
                    $.ajax({
                        url : "http://localhost/ci/admin/user/imp_del",
                        type : "post",
                        data : {'user_id':usersData[i].user_id, 'token':localStorage.token,'user_token':localStorage.user},
                        dataType : "json",
                        success : function(data){
                            if(data['token']['tag']){
                                top.layer.msg("用户删除成功！");
                                //重新加载页面
                                location.href='http://localhost/ci/admin/user/'
                            } else {
                                top.layer.msg("用户删除失败！");
                                //重新加载页面
                                location.href='http://localhost/ci/admin/user/'
                            }
                        },
                        error : function (data) {
                            console.log(data);
                            //重新加载页面
                            location.href='http://localhost/ci/admin/user/'
                        }
                    })
                }
            }
            layer.close(index);
        });
    })

    //添加会员
    $(".usersAdd_btn").click(function(){
        var index = layui.layer.open({
            title : "添加会员",
            type : 2,
            area: ['600px', '360px'],
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            content : "http://localhost/ci/admin/user/addUser",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        /*$(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);*/
    })



    //操作
    $("body").on("click",".role_edit",function(){  //编辑
        var _this = $(this);
        $('.ci_data').val(_this.attr('data-id'));
        var index = layui.layer.open({
            title : "编辑角色",
            type : 2,
            area: ['600px', '360px'],
            maxmin: true,
            shadeClose: true, //点击遮罩关闭层
            content : "http://localhost/ci/admin/userRole/index/",
            success : function(layero, index){
                layui.layer.tips('点击此处返回文章列表', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            }
        })
        //改变窗口大小时，重置弹窗的高度，防止超出可视区域（如F12调出debug的操作）
        /*$(window).resize(function(){
            layui.layer.full(index);
        })
        layui.layer.full(index);*/
        /*layer.alert('您点击了会员编辑按钮，由于是纯静态页面，所以暂时不存在编辑内容，后期会添加，敬请谅解。。。',{icon:6, title:'文章编辑'});*/
    })
/*

    $("body").on("click",".role_edit",function(){  //编辑角色.
        var _this = $(this);
        $('.ci_data').val(_this.attr('data-id'));
        $.ajax({
            url : "http://localhost/ci/admin/userRole/hello",
            type : "post",
            dataType : "json",
            data : {'user_id':_this.attr('data-id'), 'token':localStorage.token}
        });
        location.href = 'http://localhost/ci/admin/userRole/index/';
    })
*/
//查询
    $(".search_btn").click(function(){
        var userArray = [];
        if($(".search_input").val() != ''){
            var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "http://localhost/ci/admin/user/imp_find",
                    type : "get",
                    data : {'data':$(".search_input").val(), 'token':localStorage.token,'user_token':localStorage.user},
                    dataType : "json",
                    success : function(data){
                        console.log(data);
                        //usersData = JSON.parse(data)['data'];
                        usersData=data['data'];
                        usersList();
                    }
                })
                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })


//------------------------查询操作---------------
    //查询
    /*$(".search_btn").click(function(){
        var userArray = [];
        if($(".search_input").val() != ''){
            var index = layer.msg('查询中，请稍候',{icon: 16,time:false,shade:0.8});
            setTimeout(function(){
                $.ajax({
                    url : "http://localhost/ci/public/static/json/usersList.json",
                    type : "get",
                    dataType : "json",
                    success : function(data){
                        if(window.sessionStorage.getItem("addUsers")){
                            var addUsers = window.sessionStorage.getItem("addUsers");
                            usersData = JSON.parse(addUsers).concat(data);
                        }else{
                            usersData = data;
                        }
                        for(var i=0;i<usersData.length;i++){
                            var usersStr = usersData[i];
                            var selectStr = $(".search_input").val();
                            function changeStr(data){
                                var dataStr = '';
                                var showNum = data.split(eval("/"+selectStr+"/ig")).length - 1;
                                if(showNum > 1){
                                    for (var j=0;j<showNum;j++) {
                                        dataStr += data.split(eval("/"+selectStr+"/ig"))[j] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>";
                                    }
                                    dataStr += data.split(eval("/"+selectStr+"/ig"))[showNum];
                                    return dataStr;
                                }else{
                                    dataStr = data.split(eval("/"+selectStr+"/ig"))[0] + "<i style='color:#03c339;font-weight:bold;'>" + selectStr + "</i>" + data.split(eval("/"+selectStr+"/ig"))[1];
                                    return dataStr;
                                }
                            }
                            //用户名
                            if(usersStr.userName.indexOf(selectStr) > -1){
                                usersStr["userName"] = changeStr(usersStr.userName);
                            }
                            //用户邮箱
                            if(usersStr.userEmail.indexOf(selectStr) > -1){
                                usersStr["userEmail"] = changeStr(usersStr.userEmail);
                            }
                            //性别
                            if(usersStr.userSex.indexOf(selectStr) > -1){
                                usersStr["userSex"] = changeStr(usersStr.userSex);
                            }
                            //会员等级
                            if(usersStr.userGrade.indexOf(selectStr) > -1){
                                usersStr["userGrade"] = changeStr(usersStr.userGrade);
                            }
                            if(usersStr.userName.indexOf(selectStr)>-1 || usersStr.userEmail.indexOf(selectStr)>-1 || usersStr.userSex.indexOf(selectStr)>-1 || usersStr.userGrade.indexOf(selectStr)>-1){
                                userArray.push(usersStr);
                            }
                        }
                        usersData = userArray;
                        usersList(usersData);
                    }
                })
                layer.close(index);
            },2000);
        }else{
            layer.msg("请输入需要查询的内容");
        }
    })*/

})